import { ref } from 'vue'

import { userApi } from '@/apis'
import { dictToOptions } from '@/utils'

export function useFormData() {
  const dataLoading = ref(false)
  const postOptions = ref([] as OptionItem[])
  const roleOptions = ref([] as OptionItem[])

  async function getFormData(id?: string) {
    dataLoading.value = true

    const { posts, roles, postIds, roleIds } = id
      ? await userApi.getUserEditFormData(id)
      : await userApi.getUserAddFormData()

    postOptions.value = dictToOptions(posts, {
      labelKey: 'postName',
      valueKey: 'postId'
    })
    roleOptions.value = dictToOptions(roles, {
      labelKey: 'roleName',
      valueKey: 'roleId'
    })

    dataLoading.value = false

    return {
      postIds,
      roleIds
    }
  }

  return {
    dataLoading,
    postOptions,
    roleOptions,
    getFormData
  }
}
